/* Create inputs for Matlab to generate IVs  */

********** Prepare inputs
clear all
set more off
cd ""  //target directory


//compute how many HSAs each hospital system involves
clear
use "./prepare/allbasic.dta",clear
sort sysid year
egen sysyr_id=group(sysid year)
sort hsa year
egen hsayr=group(hsa year)
duplicates drop sysyr_id hsayr,force
bys sysyr_id:gen numhsa=_N
duplicates drop sysid year,force
replace numhsa=0 if sysid==0
keep sysyr_id numhsa
tempfile nhsa
save `nhsa'


//derive the markets with 1st-time-adoption stand-alone hospitals and multi-region affiliated hospitals.
//also derive the hospital systems located in the HSA above
//output the id number of the hospital systems as input to derive the internal-dominant HSA for each hospital system.
clear 
use "./prepare/allbasic.dta",clear
sort sysid year
egen sysyr_id=group(sysid year)
merge m:1 sysyr_id using `nhsa'
keep if _merge==3
drop _merge
sort hsa year
egen hsayr_id=group(hsa year)
gen sa1stadp=0
replace sa1stadp=1 if prechs==1 & adj_vnd>1 & sysid==0
bys hsayr_id:egen withsa1stadp=max(sa1stadp)
bys hsayr_id:egen withmulrsys=max(numhsa)
keep if withsa1stadp==1 & withmulrsys>1
drop if numhsa<2
duplicates drop hsayr_id sysyr_id,force
sort hsayr_id sysyr_id
outfile hsayr_id sysyr_id numhsa using "./prepare/sysyr", c replace



****** Create the input of the basic information to derive the internal-dominant HSA for each hospital system. 
clear
use "./prepare/allbasic.dta",clear
sort sysid year
egen sysyr_id=group(sysid year)
sort hsa year
egen hsayr_id=group(hsa year)
sort ahaid year
egen ahayr_id=group(ahaid year)

bys hsa year:gen nhosp=_N
gen ncompet=nhosp-1
bys hsa year:egen nadopt=total(prechs>1)
gen ratio=nadopt/ncompet
replace ratio=0 if ncompet==0


outfile sysyr_id ahayr_id hsayr_id prechs adj_vnd bdtot sysid nprofit profit teach ncompet ratio perc_mcr perc_mcd nhosp using "./prepare/input4createIV", c replace







